<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭">
    <a-card :bordered="false">
      <a-row :gutter="8">
        <a-col :span="6">
          <div>
<!--            <a-input-search v-model="searchValue"  style="margin-bottom: 8px" placeholder="Search" />-->
            <a-tree
              :auto-expand-parent="true"
              :tree-data="gData"
              :replaceFields="replaceFields"
              @select="onSelect"
              :autoExpandParent="true"
              :defaultExpandAll="true"
            >
              <template #title="{ name }">
                <!--                <span>{{name}}</span>-->
                <span v-if="name.indexOf(searchValue) > -1">
                  {{ name.substr(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ name.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ name }}</span>
              </template>
            </a-tree>
          </div>
        </a-col>
        <a-col :span="18">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <tsl-simple-query :data-source="dataSource" :columns="columns" @searchQueryTab="searchQueryTab"
                          @clearQueryTab="clearQueryTab" @initQueryColumns="initQueryColumns" :ignoreColumns="ignoreColumns"></tsl-simple-query>
<!--        <a-form layout="inline" @keyup.enter.native="searchQuery">-->
<!--          <a-row :gutter="24">-->
<!--            <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
<!--              <a-form-item label="仓库">-->
<!--                <j-search-select-tag v-model="queryParam.warehouseId" disabled dict="erp_warehouse,name,id" />-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
<!--              <a-form-item label="名称">-->
<!--                <a-input placeholder="请输入名称" v-model="queryParam.materialName"></a-input>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
<!--            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">-->
<!--              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>-->
<!--              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>-->
<!--            </span>-->
<!--            </a-col>-->
<!--          </a-row>-->
<!--        </a-form>-->
      </div>
      <!-- 查询区域-END -->
      <!-- table区域-begin -->
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          ref="table"
          size="middle"
          bordered
          :rowKey="(record,index)=>{return record.id}"
          class="j-table-force-nowrap"
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: checkval,onSelect: onSelectRow}"
          @change="handleTableChange"
          :style="{height: '300px'}">
          <template slot='htmlSlot' slot-scope='text'>
            <div v-html='text'></div>
          </template>
        </a-table>
      </div>
        </a-col>
      </a-row>
      <a-row :gutter="8">
        <a-col :span="24">
          <a-table
            ref="table1"
            size="middle"
            :scroll="{x:true}"
            bordered
            :rowKey="(record,index)=>{return record.id}"
            :columns="columns"
            :dataSource="checkSelectRows"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange , type: checkval}"
            class="j-table-force-nowrap">
          <template slot='htmlSlot' slot-scope='text'>
            <div v-html='text'></div>
          </template>
          </a-table>
        </a-col>
      </a-row>
    </a-card>

  </j-modal>
</template>
<script>
import '@/assets/less/TableExpand.less'
import {mixinDevice} from '@/utils/mixin'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import { getAction, putAction } from '@api/manage'
import TslSimpleQuery from '@comp/tsl/TslSimpleQuery.vue'


export default {
  name: 'ErpGoodsListModel',
  mixins: [JeecgListMixin, mixinDevice],
  components: { TslSimpleQuery },
  // props: ['category', "modalWidth",],
  props: {
    category: {
      type: String
    },
    modalWidth: {
      type: Number,
      required: false,
      default: 1250
    },
    checkval: {
      type: String,
      default: 'radio'
    },
    supplierId: {
      type: String,
      required: false
    },
    warehouseId: {
      type: String
    }
  },
  watch: {
    category(newval,oldval){
      console.log('Category changed to:', newValue);
      this.loadGoodsCategory();
    },
    warehouseId(newValue) {
      // 当category变更时，可以进行一些处理
      console.log('Category changed to:', newValue);
      this.queryParam = {warehouseId: newValue};
      // this.loadData();
    }
  },
  data() {
    return {
      gData:[
        {key:'1',title:"1",children:[{key:'1-1',title:"1-1"}]}
      ],
      replaceFields:{
        children:'children', title:'name', key:'code'
      },
      searchValue: '',
      description: '库存信息管理页面',
      visible: false,
      title: '选择物料',
      disableMixinCreated: true,
      isOpenSettingColumns: true,
      queryParam: {categoryCode: this.category,warehouseId:this.warehouseId},
      categoryCode: '',
      dataSource: [],
      checkSelectRows: [],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'物料分类',
          align:"center",
          dataIndex: 'categoryCode_dictText'
        },
        {
          title:'物料编号',
          align:"center",
          dataIndex: 'materialCode'
        },
        {
          title:'物料名称',
          align:"center",
          dataIndex: 'materialName'
        },
        {
          title:'仓库',
          align:"center",
          dataIndex: 'warehouseId_dictText'
        },
        {
          title:'规格型号',
          align:"center",
          dataIndex: 'noneSpec'
        },
        {
          title:'主计量单位',
          align:"center",
          dataIndex: 'meUnit_dictText'
        },
        {
          title:'库存数量',
          align:"center",
          dataIndex: 'quantity'
        },
        {
          title:'在库数量',
          align:"center",
          dataIndex: 'inStockQuantity'
        },
        {
          title:'质检中数量',
          align:"center",
          dataIndex: 'inStorageQuantity'
        },
        {
          title:'扣货数量',
          align:"center",
          dataIndex: 'frozenQuantity'
        },
        {
          title:'可用数量',
          align:"center",
          dataIndex: 'availableQuantity'
        },
        {
          title:'占用数量',
          align:"center",
          dataIndex: 'occupationQuantity'
        },
        {
          title:'辅助单位',
          align:"center",
          dataIndex: 'auUnit_dictText'
        },
        {
          title:'辅助数量',
          align:"center",
          dataIndex: 'auxiliaryQuantity'
        },
      ],
      url: {
        list: "/inventory/bussInventory/inventoryList",
        delete: "/inventory/bussInventory/delete",
        deleteBatch: "/inventory/bussInventory/deleteBatch",
        exportXlsUrl: "/inventory/bussInventory/exportXls",
        importExcelUrl: "inventory/bussInventory/importExcel",

      },
      dictOptions: {},
      superFieldList: [],
      ignoreColumns: ["id"]
    }
  },
  created() {
    this.getSuperFieldList();
      this.loadGoodsCategory();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  mounted() {
    this.loadGoodsCategory();
  },
  methods: {
    loadGoodsCategory(){
      // 加载分类
      getAction('/goods/erpGoodsCategory/categorylist',{ category: this.category}).then(res=>{
        if(res.success){
          this.gData = res.result
        }
      })
    },
    searchReset() {
      this.queryParam = {warehouseId:this.warehouseId}
      this.loadData(1);
    },
    onSelectRow(record, selected, selectedRows, nativeEvent){
      if(selected){
        this.dataSourceBack.forEach(item=>{
          if(item.id == record.id){
            this.checkSelectRows.push(item);
          }
        })
      }else{
        // this.selectedRowKeys = this.selectedRowKeys.filter(item => item !== record.id);
        this.checkSelectRows = this.checkSelectRows.filter(item => item.id != record.id);
      }
    },
    onSelect(selectedKeys, e){
      console.log('选择的值',selectedKeys,e)
      this.categoryCode = selectedKeys;
      // this.queryParam = {warehouseId:this.warehouseId, categoryCode: selectedKeys }
      this.loadData();

    },
    handleSubmit() {
      this.getGoodsSelectRows();
      // this.searchReset(false)
      this.onClearSelected();
      this.close();
    },
    add() {
      this.showModal();
    },
    showModal() {
      this.dataSource = []
      this.visible = true;
      this.loadData();
    },
    getGoodsSelectRows() {
      let selectedRow = null;
      if(this.checkval=='radio'){
         selectedRow = this.selectionRows[0];
      }else{
         selectedRow = this.selectionRows
      }
      // let selectedRow = this.selectionRows[0];
      //传递选中的数据
      this.$emit("handlerOk", this.checkSelectRows);
      this.checkSelectRows = []
      this.selectionRows = []
      this.selectedRowKeys = []
      this.queryParam = {}
    },
    initDictConfig() {
    },
    close() {
      this.searchReset(false);
      this.checkSelectRows = []
      this.selectedRowKeys = []
      this.selectionRows = []
      this.visible = false;
    },
    getSuperFieldList() {
      let fieldList=[];
      fieldList.push({type:'string',value:'warehouseId',text:'仓库',dictCode:"erp_warehouse,name,id"})
      fieldList.push({type:'string',value:'categoryCode',text:'物料分类',dictCode:"erp_goods_category,name,code"})
      fieldList.push({type:'string',value:'status',text:'物料状态',dictCode:'dict_item_status'})
      fieldList.push({type:'string',value:'materialCode',text:'物料编号',dictCode:''})
      fieldList.push({type:'string',value:'materialName',text:'物料名称',dictCode:''})
      fieldList.push({type:'string',value:'customerMaterialCode',text:'客户物料编号',dictCode:''})
      fieldList.push({type:'string',value:'noneSpec',text:'规格型号',dictCode:''})
      fieldList.push({type:'string',value:'meUnit',text:'主计量单位',dictCode:'ji_unit'})
      fieldList.push({type:'string',value:'month',text:'月份',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'receivedQuantity',text:'本期收到数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'issuedQuantity',text:'本期发出数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'endingBalanceQuantity',text:'期末余额数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'openingBalanceQuantity',text:'期初余额数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'quantity',text:'库存数量',dictCode:''})
      fieldList.push({type:'string',value:'auUnit',text:'辅助单位',dictCode:'zl_unit'})
      fieldList.push({type:'BigDecimal',value:'auxiliaryQuantity',text:'辅助数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'inStockQuantity',text:'在库数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'inStorageQuantity',text:'入库中数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'frozenQuantity',text:'冻结数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'occupationQuantity',text:'占用数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'availableQuantity',text:'可用数量',dictCode:''})
      fieldList.push({type:'string',value:'spareOne',text:'备用字段一',dictCode:''})
      fieldList.push({type:'string',value:'spareTwo',text:'备用字段二',dictCode:''})
      fieldList.push({type:'string',value:'spareThree',text:'备用字段三',dictCode:''})
      fieldList.push({type:'string',value:'spareFour',text:'备用字段四',dictCode:''})
      fieldList.push({type:'string',value:'spareFive',text:'备用字段五',dictCode:''})
      fieldList.push({type:'string',value:'isHaveOrder',text:'是否有采购订单',dictCode:''})
      this.superFieldList = fieldList
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      if(this.supplierId){
        params.supplierId = this.supplierId;
      }
      if(this.category){
        params.categoryCode = this.category
      }
      if(this.categoryCode){
        params.categoryCode = this.categoryCode
      }
      if(this.warehouseId){
        params.warehouseId = this.warehouseId
      }
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result;
          this.dataSourceBack = this.dataSource
          // this.$refs.outletquote.searchQueryTab()
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>